import Vue from "vue";
import Vuex from "vuex";
import { getMenuList } from "@/api";
import allRouters from "../router/allRouters";
import recursionRoutes from "../utils/recursionRoutes";
import dynamicRouters from "../router/dynamicRoutes";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    // 存储用户权限
    menuList: [],
    // 存储面包屑路由
    breadcrumb: [],
  },
  mutations: {
    GET_SIDEMENU(state, payload) {
      // 将得到的正确权限赋值给 state 内的存储权限数组
      state.menuList = payload;
      // 遍历鉴权文件内的数组，返回对应对象
      let home = dynamicRouters.find((item) => item.path === "/");
      // 往对应对象内新增 children 属性
      home["children"] = state.menuList;
    },
    GET_ROLENAME(state, payload) {
      state.roleName = payload;
    },
    GET_BREADCRUMB(state, payload) {
      state.breadcrumb = payload;
    },
  },
  actions: {
    async SET_SIDEMENU({ commit }) {
      // 调用请求对应权限接口
      let res = await getMenuList();
      // 判断是否请求成功并且带有权限的数组数量大于0
      if (res.data.state && res.data.menuList.length > 0) {
        // 调用递归对比函数得到正确的权限
        var userMenu = recursionRoutes(allRouters, res.data.menuList);
      }
      // 发送到 mutations 内做下一步处理
      commit("GET_SIDEMENU", userMenu);
    },
  },
  modules: {},
});
